package com.xyazm.inventory.processor;

import com.xyazm.inventory.dao.ProductStockDAO;
import com.xyazm.inventory.dao.ProductStockLogDAO;
import com.xyazm.inventory.domain.entity.ProductStockLogDO;
import com.xyazm.inventory.enums.StockLogStatusEnum;
import com.xyazm.inventory.exception.InventoryBizException;
import com.xyazm.inventory.exception.InventoryErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 释放商品库存处理器
 * @author xuyou
 * @date 2022年07月30日 15:26
 */
@Slf4j
@Component
public class ReleaseProductStockProcessor {

    @Autowired
    private ProductStockDAO productStockDAO;

    @Autowired
    private ProductStockLogDAO productStockLogDAO;

    /**
     * 执行释放商品库存逻辑
     * @author xuyou
     * 2022/7/30 0030 15:31
     * @param skuCode
     * @param saleQuantity
     * @param productStockLog
    */
    @Transactional(rollbackFor = Exception.class)
    public void doRelease(String skuCode, Integer saleQuantity, ProductStockLogDO productStockLog) {

        //1、执行mysql释放商品库存逻辑
        int nums = productStockDAO.releaseProductStock(skuCode, saleQuantity);
        if(nums <= 0) {
            throw new InventoryBizException(InventoryErrorCodeEnum.RELEASE_PRODUCT_SKU_STOCK_ERROR);
        }

        //2、更新库存日志的状态为"已释放"
        if(null != productStockLog) {
            productStockLogDAO.updateStatus(productStockLog.getId(), StockLogStatusEnum.RELEASED.getCode());
        }
    }
}
